<?php

namespace app\api\model\wanlshop;

use app\common\model\User;
use fast\Random;
use think\Model;

class UserInvitation extends Model
{
    protected $name = 'user_invitation';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public static function addRecord($user_id, $invitation_user_id)
    {
        self::create([
            'user_id' => $user_id,
            'invitation_user_id' => $invitation_user_id,
        ]);
    }

    public static function generateCode()
    {
        $code = Random::alnum(11);
        if (User::where('invitation_code', $code)->find()) {
            self::generateCode();
        }
        return $code;
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'invitation_user_id', 'id');
    }
}
